package com.mc.fastkit.ui

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.view.MotionEvent
import android.widget.EditText
import androidx.activity.result.ActivityResult
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityOptionsCompat
import com.mc.fastkit.utils.KeyboardUtils
import com.mc.fastkit.utils.ViewUtils
import com.mc.fastkit.widget.ActivityResultHelper

/**
 * BaseActivity
 * @author: MasterChan
 * @date: 2023-02-18 22:05
 */
open class BaseActivity : AppCompatActivity() {

    protected lateinit var context: Context
    protected lateinit var activity: AppCompatActivity

    /**
     * StartForActivityResult工具
     */
    private val resultHelper = ActivityResultHelper()

    /**
     * 是否自动收起键盘
     */
    protected open var isAutoHideKeyboard = true

    /**
     * 是否仅支持竖屏
     */
    protected open var isOnlyPortrait = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        context = this
        activity = this
        resultHelper.register(this)
        requestedOrientation = if (isOnlyPortrait) {
            ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        } else {
            ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
        }
    }

    override fun dispatchTouchEvent(event: MotionEvent): Boolean {
        if (isAutoHideKeyboard && event.action == MotionEvent.ACTION_DOWN) {
            val view = currentFocus
            if (view is EditText && !ViewUtils.isPointOnView(view, event.x, event.y)) {
                KeyboardUtils.hideKeyboard(view)
            }
        }
        return super.dispatchTouchEvent(event)
    }

    open fun startActivityForResult(clazz: Class<out Activity>, result: (ActivityResult) -> Unit) {
        resultHelper.launch(clazz, result)
    }

    open fun startActivityForResult(
        intent: Intent,
        options: ActivityOptionsCompat? = null,
        result: (ActivityResult) -> Unit
    ) {
        resultHelper.launch(intent, options, result)
    }
}